package cn.itsource.config;

import cn.dev33.satoken.stp.StpInterface;
import cn.itsource.constants.CacheConstants;
import cn.itsource.constants.RConst;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 自定义权限加载接口实现类
 */
    // 保证此类被 自动加载，完成 Sa-Token 的自定义权限验证扩展
@Data
public class StpInterfaceImpl implements StpInterface {

    private RedisTemplate<String,Object> redisTemplate;

    public StpInterfaceImpl() {
    }

    public StpInterfaceImpl(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    /**
     * 返回一个账号所拥有的权限码集合 
     */
    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        String key = CacheConstants.CURRENT_LOGIN_PERMISSION+loginId.toString();
        //先查询缓存
        if(redisTemplate.hasKey(key)){
            List<String> permissionList =  (List<String>)redisTemplate.opsForValue().get(key);
            redisTemplate.opsForValue().set(key,permissionList, RConst.Num.INT_30, TimeUnit.MINUTES);
            return permissionList;
        }
        return null;
    }

    /**
     * 返回一个账号所拥有的角色标识集合 (权限与角色可分开校验)
     */
    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        // 本 list 仅做模拟，实际项目中要根据具体业务逻辑来查询角色
        List<String> list = new ArrayList<String>();    
        list.add("admin");
        list.add("super-admin");
        return list;
    }

}
